package org.yuankan.yuankanmanagerserver.service;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

import okhttp3.*;


@Service
public class AiListService {

    // Deepseek API 调用方法
    @Value("${deepseekApiKey}")
    private String deepseekApiKey;

    @Value("${wenxinyiyanApiKey}")
    private String wenxinyiyanApiKey;

    @Value("${qianfanApiKey}")
    private String qianfanApiKey;

    @Value("${qianfanApiSecret}")
    private String qianfanApiSecret;


    public String callDeepseekApi(String input) {
        try {
            // DeepSeek API的URL
            String apiUrl = "https://api.deepseek.com/v1/chat/completions";


            // 创建URL对象
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            // 设置请求头，包括API Key和Content-Type
            connection.setRequestProperty("Authorization", "Bearer " + deepseekApiKey);
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);

            // 准备JSON数据
            JSONObject jsonInput = new JSONObject();
            jsonInput.put("model", "deepseek-chat");

            JSONObject messages = new JSONObject();
            JSONObject systemMessage = new JSONObject();
            systemMessage.put("role", "system");
            systemMessage.put("content", "You are a helpful assistant");

            JSONObject userMessage = new JSONObject();
            userMessage.put("role", "user");
            userMessage.put("content", input);
            JSONArray messagesList = new JSONArray();
            messagesList.add(systemMessage);
            messagesList.add(userMessage);

            messages.put("messages", messagesList);


            jsonInput.put("messages", messages);
            jsonInput.put("stream", false);

            // 发送POST输出
            try (OutputStream os = connection.getOutputStream()) {
                byte[] inputByte = jsonInput.toString().getBytes("utf-8");
                os.write(inputByte, 0, inputByte.length);
            }

            // 读取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                try (var reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = reader.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    // 解析响应JSON
                    JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                    JSONArray choices = jsonResponse.getJSONArray("choices");
                    JSONObject firstChoice = choices.getJSONObject(0);
                    JSONObject message = firstChoice.getJSONObject("message");
                    String content = message.getString("content");
                    System.out.println(content);
                    return content;
                }
            } else {
                System.out.println("GET request not worked. Response Code: " + responseCode);
                return "Error calling Deepseek API";

            }

        } catch (Exception e) {
            e.printStackTrace();
            return "Error calling Deepseek API";
        }
    }

    // 文心一言 API 调用方法
    public String callWenxinApi(String input) {
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://api.wenxin.baidu.com/v1/chat"))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString("{\"prompt\": \"" + input + "\"}"))
                    .build();

            HttpResponse<String> response = HttpClient.newHttpClient()
                    .send(request, HttpResponse.BodyHandlers.ofString());

            return response.body();
        } catch (Exception e) {
            e.printStackTrace();
            return "Error calling Wenxin API";
        }
    }


    public String callQianFanApi(String content) {

        OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\"messages\":[{\"role\":\"user\",\"content\":\""+ content+ "\"}]}");
        Request request = null;
        try {
            request = new Request.Builder()
                    .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=" + getAccessToken())
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Response response = null;
        try {
            response = HTTP_CLIENT.newCall(request).execute();
            return JSONObject.parseObject(response.body().string()).getString("result");

        } catch (IOException e) {
            e.printStackTrace();
            return "Error calling QianFan API";
        } finally {
            if (response != null) response.close();
            HTTP_CLIENT.dispatcher().executorService().shutdown();

        }


    }

    String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + qianfanApiKey
                + "&client_secret=" + qianfanApiSecret);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return JSONObject.parseObject(response.body().string()).getString("access_token");
    }
}



